// 设置页面JavaScript逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const elements = {
        homeTab: document.getElementById('home-tab'),
        settingsTab: document.getElementById('settings-tab'),
        payDate: document.getElementById('payDate'),
        monthlySalary: document.getElementById('monthlySalary'),
        yearlyBonus: document.getElementById('yearlyBonus'),
        includeWeekends: document.getElementById('includeWeekends'),
        saveButton: document.getElementById('saveSettings'),
        resetButton: document.getElementById('resetSettings'),
        settingsForm: document.getElementById('settingsForm'),
        loadingOverlay: document.getElementById('loadingOverlay')
    };

    // 验证元素是否存在
    if (!elements.payDate || !elements.monthlySalary || !elements.includeWeekends || !elements.saveButton) {
        console.error('Required elements not found');
        return;
    }

    // Tab切换功能
    if (elements.homeTab) {
        elements.homeTab.addEventListener('click', function() {
            window.location.href = '../home/index.html';
        });
    }

    // 显示/隐藏加载动画
    function toggleLoading(show) {
        if (elements.loadingOverlay) {
            elements.loadingOverlay.style.display = show ? 'flex' : 'none';
        }
    }

    // 表单验证
    function validateForm() {
        const payDate = parseInt(elements.payDate.value);
        const monthlySalary = parseFloat(elements.monthlySalary.value);
        const yearlyBonus = parseFloat(elements.yearlyBonus.value);
        
        if (isNaN(payDate) || payDate < 1 || payDate > 31) {
            CowHorseClock.showToast('发薪日必须在1-31之间', 'error');
            elements.payDate.focus();
            return false;
        }
        
        if (isNaN(monthlySalary) || monthlySalary < 0) {
            CowHorseClock.showToast('月薪必须大于等于0', 'error');
            elements.monthlySalary.focus();
            return false;
        }
        
        if (isNaN(yearlyBonus) || yearlyBonus < 0) {
            CowHorseClock.showToast('年终奖必须大于等于0', 'error');
            elements.yearlyBonus.focus();
            return false;
        }
        
        return true;
    }

    // 保存设置
    function saveSettings() {
        if (!validateForm()) {
            return;
        }

        toggleLoading(true);

        const settings = {
            payDate: parseInt(elements.payDate.value),
            monthlySalary: parseFloat(elements.monthlySalary.value),
            yearlyBonus: parseFloat(elements.yearlyBonus.value),
            includeWeekends: elements.includeWeekends.checked
        };

        setTimeout(() => {
            try {
                CowHorseClock.saveSettings(settings);
                
                // 添加保存动画效果
                elements.saveButton.innerHTML = '<span class="icon">✅</span>已保存';
                elements.saveButton.style.background = 'linear-gradient(135deg, #34c759, #30a46c)';
                
                setTimeout(() => {
                    elements.saveButton.innerHTML = '<span class="icon">💾</span>保存设置';
                    elements.saveButton.style.background = 'linear-gradient(135deg, var(--primary-color), var(--success-color))';
                }, 2000);
                
                CowHorseClock.showToast('设置已保存');
                
                // 如果月薪大于0，显示成功提示
                if (settings.monthlySalary > 0) {
                    setTimeout(() => {
                        CowHorseClock.showToast('工资计算已配置完成！', 'success');
                    }, 2500);
                }
                
            } catch (error) {
                console.error('Error saving settings:', error);
                CowHorseClock.showToast('保存失败，请重试', 'error');
            } finally {
                toggleLoading(false);
            }
        }, 500);
    }

    // 重置设置
    function resetSettings() {
        if (confirm('确定要重置所有设置为默认值吗？此操作不可撤销。')) {
            toggleLoading(true);
            
            setTimeout(() => {
                try {
                    // 重置为默认设置
                    const defaultSettings = CowHorseClock.defaultSettings;
                    CowHorseClock.saveSettings(defaultSettings);
                    
                    // 更新表单
                    elements.payDate.value = defaultSettings.payDate;
                    elements.monthlySalary.value = defaultSettings.monthlySalary.toFixed(2);
                    elements.yearlyBonus.value = defaultSettings.yearlyBonus.toFixed(2);
                    elements.includeWeekends.checked = defaultSettings.includeWeekends;
                    
                    // 添加重置动画效果
                    elements.resetButton.innerHTML = '<span class="icon">✅</span>已重置';
                    elements.resetButton.style.backgroundColor = '#34c759';
                    
                    setTimeout(() => {
                        elements.resetButton.innerHTML = '<span class="icon">🔄</span>重置为默认设置';
                        elements.resetButton.style.backgroundColor = 'var(--background-secondary)';
                    }, 2000);
                    
                    CowHorseClock.showToast('设置已重置为默认值');
                    
                } catch (error) {
                    console.error('Error resetting settings:', error);
                    CowHorseClock.showToast('重置失败，请重试', 'error');
                } finally {
                    toggleLoading(false);
                }
            }, 500);
        }
    }

    // 加载设置到表单
    function loadSettings() {
        try {
            const settings = CowHorseClock.getStoredSettings();
            
            elements.payDate.value = settings.payDate;
            elements.monthlySalary.value = settings.monthlySalary.toFixed(2);
            elements.yearlyBonus.value = settings.yearlyBonus.toFixed(2);
            elements.includeWeekends.checked = settings.includeWeekends;
            
            // 更新checkbox的aria属性
            const checkmark = elements.includeWeekends.nextElementSibling;
            if (checkmark) {
                checkmark.setAttribute('aria-checked', settings.includeWeekends);
            }
            
        } catch (error) {
            console.error('Error loading settings:', error);
            CowHorseClock.showToast('加载设置失败', 'error');
        }
    }

    // 实时输入验证
    elements.payDate.addEventListener('input', function() {
        const value = parseInt(this.value);
        if (value < 1) this.value = 1;
        if (value > 31) this.value = 31;
        
        // 移除错误状态
        this.style.borderColor = 'var(--border-color)';
    });

    elements.monthlySalary.addEventListener('input', function() {
        const value = parseFloat(this.value);
        if (value < 0) this.value = 0;
        
        // 移除错误状态
        this.style.borderColor = 'var(--border-color)';
    });

    elements.yearlyBonus.addEventListener('input', function() {
        const value = parseFloat(this.value);
        if (value < 0) this.value = 0;
        
        // 移除错误状态
        this.style.borderColor = 'var(--border-color)';
    });

    // 更新checkbox的aria属性
    elements.includeWeekends.addEventListener('change', function() {
        const checkmark = this.nextElementSibling;
        if (checkmark) {
            checkmark.setAttribute('aria-checked', this.checked);
        }
    });

    // 事件监听器
    elements.saveButton.addEventListener('click', saveSettings);
    
    if (elements.resetButton) {
        elements.resetButton.addEventListener('click', resetSettings);
    }
    
    // 表单提交事件
    if (elements.settingsForm) {
        elements.settingsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveSettings();
        });
    }
    
    // 支持回车键保存
    elements.payDate.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveSettings();
        }
    });
    
    elements.monthlySalary.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveSettings();
        }
    });

    elements.yearlyBonus.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveSettings();
        }
    });

    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl+S 或 Cmd+S 保存
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            saveSettings();
        }
        
        // Ctrl+R 或 Cmd+R 重置
        if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
            e.preventDefault();
            if (elements.resetButton) {
                resetSettings();
            }
        }
    });

    // 页面加载时加载设置
    loadSettings();

    // 检查是否首次使用
    const settings = CowHorseClock.getStoredSettings();
    if (settings.monthlySalary === 0) {
        setTimeout(() => {
            CowHorseClock.showToast('欢迎使用牛马时钟！请先配置您的工资信息', 'warning');
        }, 500);
    }

    // 监听storage变化，实现多标签页同步
    window.addEventListener('storage', function(e) {
        if (e.key === 'cowHorseClockSettings') {
            loadSettings();
        }
    });
});